package dkbta.ontology.elements.abstractions.rate;

import java.util.Collection;
import java.util.List;

import dkbta.ontology.elements.Element;
import dkbta.ontology.elements.abstractions.PairedMappingFunction;
import dkbta.ontology.elements.abstractions.interpolation.PersistenceFunction;
import dkbta.ontology.values.NumericValues;

public class RateMappingFunction extends PairedMappingFunction<Rate>{
	private final Collection<Entry> _entries;

	public RateMappingFunction(Collection<Entry> entries){
		_entries = entries;
	}

	@Override
	protected String calculateValue(double variationPerMillisecond){
		variationPerMillisecond = Math.abs(variationPerMillisecond);
		for (Entry e : _entries){
			String mappedValue = e.attemptToMap(variationPerMillisecond);
			if (mappedValue != null){
				return mappedValue;
			}
		}
		return null;
	}

	@Override
	protected void mapElements(List<Rate> abstractions, String abstractionName,
		Element before, Element after, PersistenceFunction interpolation){
		String value = mapPair(before, after, interpolation);
		if (value != null){
			abstractions.add(new Rate(abstractionName, before.getTimeInterval()
					.getStartTime(), after.getTimeInterval().getEndTime(), value));
		}
	}

	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		for (Entry e : _entries){
			sb.append("\r\n\t");
			sb.append(e);
		}
		return sb.toString();
	}

	public static class Entry{
		private final String _mappedValue;

		private final NumericValues _validValues;

		public Entry(String mappedValue, NumericValues validValues){
			_mappedValue = mappedValue;
			_validValues = validValues;
		}

		public String attemptToMap(double value){
			return (_validValues.isValid(value)) ? _mappedValue : null;
		}

		@Override
		public String toString(){
			return _mappedValue + " - " + _validValues;
		}
	}

}
